package codec

import (
	"encoding/gob"
	"io"

	"gitlab.com/elaina/std-go/rpc/protoc"
)

func NewGobCodecConn(conn io.ReadWriteCloser) CodecConn {
	return &GobCodecConn{
		conn:    conn,
		encoder: gob.NewEncoder(conn),
		decoder: gob.NewDecoder(conn),
	}
}

type GobCodecConn struct {
	conn    io.ReadWriteCloser
	encoder *gob.Encoder
	decoder *gob.Decoder
}

func (gc *GobCodecConn) Write(header *protoc.Header, body interface{}) error {
	if err := gc.encoder.Encode(header); err != nil {
		return err
	}
	if err := gc.encoder.Encode(body); err != nil {
		return err
	}
	return nil
}

func (gc *GobCodecConn) ReadHeader(header *protoc.Header) error {
	return gc.decoder.Decode(header)
}

func (gc *GobCodecConn) ReadBody(body interface{}) error {
	return gc.decoder.Decode(body)
}

func (gc *GobCodecConn) Close() error {
	return gc.conn.Close()
}
